//
//  DownloadUpdatesOperation.m
//  ABlip
//
//  Created by dawid on 09-02-13.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "DownloadUpdatesOperation.h"
#import "BlipRequestUpdate.h"
#import "AppController.h"
#import "JSON/JSON.h"
#import "ABlipConstants.h"
#import "BlipErrors.h"
#import "RegexKitLite.h"

@implementation DownloadUpdatesOperation


- (id)initWithType:(int)type operationLock:(NSLock*)opLock
{
	if (![super init]) 
		return nil;
	requestType = type;
	opLock = lock;
    return self;
}
- (void)dealloc {

    [super dealloc];
}

- (void)main {
	//while ([lock tryLock] == NO){
	// usleep(10000);
	 
	 //} 
	

	
	[[AppController shared] stopTimer];
	[[AppController shared] hideRefreshButton];
	NSData *urlData;
	NSURLResponse *responce;
	NSError *error;
	NSURL *urlResp ;
	BLP_URLRequestUpdate *request = [[BLP_URLRequestUpdate alloc] initGetMethodWithLogin:[[AppController shared]lastUpdateId]:[[AppController shared]userPassword]];
	
	int tryCount = 3;
	
	while (tryCount >0){
		tryCount--;
		
		urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responce error:&error];
		if (!urlData){
#ifdef __DEBUG__
			NSLog(@"urlData=nil in sendRequest");
#endif
			
			continue;
		} else{
			if ([BlipErrors findError:urlData]){
				if (tryCount == 0)
					[[AppController shared] displayAlertWithMessageText:[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]];
				continue;
			}
		}
		break;
	}
	
	[urlResp release];
	urlResp =nil;	
	
	NSString* respString = [[AppController shared] checkDownloadData:urlData];
	if (!respString){
#ifdef __DEBUG__
		NSLog(@"nic w resp");
#endif
		[request release];
		request = nil;
		[[AppController shared] initializeTimer];
		//[[AppController shared] resetTextBox];
		[[AppController shared] unHideRefreshButtton];
		return;
	}
	
	if ([[AppController shared] isFirstRun]==YES && [[AppController shared] hideGrowlNotif] == YES)
		[[AppController shared] sendGrowlDownloadingMsg];

	NSString *userLogin  = [[AppController shared] userLogin];
	
	NSMutableArray* userNames = [[AppController shared] userNames];
	if (![[AppController shared] blipMessages]){
				[[AppController shared] createBlipMsg];
	}
	NSMutableArray* blipMessages = [[AppController shared] blipMessages];
	
	if (respString){
		NSMutableArray *jsonValues = [respString JSONValue];
		if (!jsonValues){
#ifdef __DEBUG__
			NSLog(@"jsonValues array is empty!!");
#endif
			[[AppController shared] unHideRefreshButtton];
		}else {
			int i;
			NSString *userName;
			BlipMessage *message;
			for (i =[jsonValues count]-1; i >=0; i--){
				message = [[BlipMessage alloc] initWithJSON:[jsonValues objectAtIndex:i] authorization:[[AppController shared]userPassword]];
				[blipMessages addObject:message];
				
				userName = [message userName];
				if ([[[message msgType] stringValue] isMatchedByRegex:ABL_REGEX_DELETE_TYPES] == YES){
					if (userName!=nil && [userName isEqualToString:userLogin] == YES){
						[message setCanDeleteMessage:YES];
					}
				}
				
				if(userName !=nil && [userNames containsObject:userName]==NO){
					[userNames addObject:userName];
				}
				
				userName = [message recipientName];
				if(userName !=nil && [userNames containsObject:userName]==NO){
					[userNames addObject:userName];
				}

				[message release];
				//message = nil;
				
			}
			
			if ([blipMessages count]>0){
				[[AppController shared] setLastUpdateId:[[blipMessages lastObject] msgId]];
		//		[[[AppController shared] setLastUpdateId:[blipMessages objectAtIndex:[blipMessages count]-1] msgId];
			}
			
			//zapisanie nazw user'ow
			NSMutableArray* temp = [[NSMutableArray alloc] initWithArray:[userNames sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]];
			if (userNames){
				[userNames  release];
				userNames = nil;
			}
			userNames = temp;
			
			int counter =3;
			NSString *path = [[AppController appSupportDir] stringByAppendingPathComponent:BLIP_USERS_PATH];
			while (counter > 0){
				if ([NSKeyedArchiver archiveRootObject:userNames toFile:path] == YES)
					break;
				usleep(1000);
				counter--;
			}
			
		}
		jsonValues = nil;
		
	}
	
	
	
	

	[request release];
	request = nil;
	
	int counter = 0;
	int moreMsgCount = [blipMessages count] - MAX_GROWL_MSG_IN_OPERATION;
	for (BlipMessage *msg in blipMessages) {

        [msg downloadSynchronousExtendedMsg];
		
		counter++;
		
		if ([[AppController shared] hideGrowlNotif] == YES){
			if ([[AppController shared] isFirstRun] == NO){
				if (counter>MAX_GROWL_MSG_IN_OPERATION){
					if (counter ==MAX_GROWL_MSG_IN_OPERATION+1)
					{
						[[AppController shared] sendGrowlMoreMessages:[NSString stringWithFormat:@"%d", moreMsgCount]];
					}
				}else {
					[[AppController shared] sendGrowlMessage:msg];
					
				}
			}
		}
		
		
    }
#ifdef __DEBUG__
	NSLog(@"blipmsg w downloadOperation = %d", [[[AppController shared] blipMessages] count]);
	NSLog(@"last msg id = %@", [[AppController shared] lastUpdateId]);
#endif
	
	[[AppController shared] performSelectorOnMainThread:@selector(tryRefreshView:)
											 withObject:@""
										  waitUntilDone:YES];
	

	//[lock unlock];
    
}


@end
